package com.aurora.source.authority.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aurora.source.R;
import com.aurora.source.authority.adapter.PersonAuthAdapter;
import com.aurora.source.authority.bean.ProcessDataBean;
import com.aurora.source.authority.bean.PersonAuthBean;
import com.aurora.source.authority.bean.SysAuthDataBean;
import com.aurora.source.authority.presenter.AuthManagePresenter;
import com.aurora.source.authority.view.IAuthManageView;
import com.aurora.source.base.BaseWhiteToolbarActivity;
import com.aurora.source.entity.UserEntity;
import com.aurora.source.util.GreenDaoHelper;
import com.aurora.source.util.SPUtils;
import com.aurora.source.widget.RxDialogSureCancel;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author: ww
 * @description:权限管理
 * @date: 2018/9/10
 */
public class AuthManageActivity extends BaseWhiteToolbarActivity<AuthManagePresenter> implements IAuthManageView {


    private static final int CHANGE_AUTH = 10000;//改变授权
    private static final int ADD_PERSON = 10001;//添加账号
    @BindView(R.id.fab_add)
    Button fabAdd;
    @BindView(R.id.rv_person_auth_list)
    RecyclerView rvPersonAuthList;
    @BindView(R.id.iv_home)
    ImageView ivHome;
    @BindView(R.id.tv_home)
    TextView tvHome;
    @BindView(R.id.ll_home)
    LinearLayout llHome;
    @BindView(R.id.iv_source)
    ImageView ivSource;
    @BindView(R.id.tv_source)
    TextView tvSource;
    @BindView(R.id.ll_source)
    LinearLayout llSource;
    @BindView(R.id.iv_setting)
    ImageView ivSetting;
    @BindView(R.id.tv_setting)
    TextView tvSetting;
    @BindView(R.id.ll_setting)
    LinearLayout llSetting;
    PersonAuthAdapter personAuthAdapter;
    PersonAuthBean.UserInfoDTOListBean userInfoDTOListBean;//选择操作谁
    @BindView(R.id.et_key)
    EditText etKey;
    @BindView(R.id.iv_search)
    ImageView ivSearch;


    @Override
    public AuthManagePresenter attach() {
        return new AuthManagePresenter(this);
    }

    @Override
    public int bindLayout() {
        return R.layout.activity_auth_manage_main;
    }

    @Override
    public void initData(@Nullable Bundle bundle) {


    }

    public void refreshUI() {
        List<UserEntity> userEntities = GreenDaoHelper.getDaoSession().getUserEntityDao().loadAll();
        Map<String, String> params = new HashMap<>();
        params.put("parentUserId", (String) SPUtils.get(activity, SPUtils.USER_ID, ""));
        params.put("userName", etKey.getText().toString());

        //     params.put("userName", );
        //    params.put("userName",userEntities.get(0).getUserName());
        basePresenter.AuthManage(activity, params);
    }

    @Override
    public void initView(Bundle savedInstanceState, View contentView) {
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        simpleToolbar.setMainTitle("权限管理");
        simpleToolbar.setLeftVisibility(View.VISIBLE);

        personAuthAdapter = new PersonAuthAdapter();
        rvPersonAuthList.setAdapter(personAuthAdapter);
        rvPersonAuthList.setLayoutManager(new LinearLayoutManager(this));
        personAuthAdapter.setOnAuthClick(new PersonAuthAdapter.OnAuthClick() { //授权
            @Override
            public void onAuthClick(PersonAuthBean.UserInfoDTOListBean data, int position) {
                userInfoDTOListBean = data;
                Bundle bundle = new Bundle();
                bundle.putSerializable("selectProcess", (Serializable) data.getProcessList());
                bundle.putSerializable("selectSysAuths", (Serializable) data.getSysRoleList());
                gotoActivityForResult(AddJurisdictionActivity.class, CHANGE_AUTH, bundle);
            }
        });
        personAuthAdapter.setOnDeleteClick(new PersonAuthAdapter.OnRegistClick() { //冻结，解冻
            @Override
            public void onRegistClick(PersonAuthBean.UserInfoDTOListBean data, int position) {
                userInfoDTOListBean = data;
                showDeletePop(userInfoDTOListBean.getUserStatus());
            }
        });
    }

    @Override
    public void doBusiness() {
        refreshUI();
    }

    //注销
    private void showDeletePop(final String userStatus) {
        final RxDialogSureCancel rxDialogSureCancel = new RxDialogSureCancel(activity);
        if(userStatus.equals("SUCCESS")){
            rxDialogSureCancel.setTitle("确定冻结账户");
        }else {
            rxDialogSureCancel.setTitle("确定解冻账户");
        }

        rxDialogSureCancel.setContent(userInfoDTOListBean.getUserName());

        rxDialogSureCancel.setSureListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String mUserState = userStatus;
                String userAccount = userInfoDTOListBean.getUserAccount();
                if(userStatus.equals("SUCCESS")){
                    mUserState="01";//冻结
                }else {
                    mUserState="00";//解冻
                }
                basePresenter.regist(activity, userAccount, mUserState);
                rxDialogSureCancel.cancel();
            }
        });
        rxDialogSureCancel.setCancelListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rxDialogSureCancel.cancel();
            }
        });
        rxDialogSureCancel.show();
    }


    @OnClick({R.id.iv_search, R.id.fab_add, R.id.ll_home, R.id.ll_source, R.id.ll_setting})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_search:
                refreshUI();
                break;
            case R.id.fab_add:
                gotoActivityForResult(PersonAuthAddActivity.class, ADD_PERSON);
                break;
            case R.id.ll_home:
                break;
            case R.id.ll_source:
                break;
            case R.id.ll_setting:
                break;

        }
    }

    @Override
    public void onAuthManageSuccess(PersonAuthBean data) {
        personAuthAdapter.setDataList(data.getUserInfoDTOList());
    }

    @Override
    public void onAuthManageFail(String msg) {
        showToast(msg);
    }

    @Override
    public void onRegistFail(String msg) {
        showToast(msg);
    }

    @Override
    public void onRegistSuccess(String msg) {
        showToast(msg);
        refreshUI();
    }

    @Override
    public void onUpdataSuccess(String msg) {
        showToast(msg);
        refreshUI();
    }

    @Override
    public void onUpdataFail(String msg) {
        showToast(msg);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ADD_PERSON) { //添加账号
            refreshUI();
        } else if (requestCode == CHANGE_AUTH) { //授权
            if (resultCode == RESULT_OK) { //修改授权
                List<ProcessDataBean.ProcessListBean> dataList = (List<ProcessDataBean.ProcessListBean>) data.getSerializableExtra("data1");
                List<SysAuthDataBean.SystemRoleDTOListBean> dataList2 = (List<SysAuthDataBean.SystemRoleDTOListBean>) data.getSerializableExtra("data2");
                String processIds = "";
                String sysRoleCode = "";
                if (dataList == null || dataList.size() == 0) {
                    processIds = "";
                } else {
                    for (ProcessDataBean.ProcessListBean e : dataList) {
                        if (e.isSelect()) {
                            processIds = String.format("%s%s", processIds, e.getProcessId() + ",");
                        }
                    }
                    if (!TextUtils.isEmpty(processIds)) {
                        processIds = processIds.substring(0, processIds.length() - 1);
                    }
                }


                if (dataList2 == null || dataList2.size() == 0) {
                    sysRoleCode = "";
                } else {
                    for (SysAuthDataBean.SystemRoleDTOListBean e : dataList2) {
                        if (e.isSelect()) {
                            sysRoleCode = String.format("%s%s", sysRoleCode, e.getSysRoleCode() + ",");
                        }
                    }
                    if (!TextUtils.isEmpty(sysRoleCode)) {
                        sysRoleCode = sysRoleCode.substring(0, sysRoleCode.length() - 1);
                    }
                }

                basePresenter.updateUserRole(userInfoDTOListBean.getUserId(), processIds,sysRoleCode);
            }
        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
